/*uploader*/
;(function($,window,document,undefined){
	var Uploader = function(elem, options){
		this.$elem = $(elem);
		this.$container = this.$elem.parents(".uploaded-container");
		this.options = options;
	};
	Uploader.prototype = {
		defaults: {
			fileType: ["jpg", "png", "bmp", "jpeg"],
        	fileSize: 1024 * 1024 * 10,
        	upload_target:'',
        	remove_target:'',
        	upload_session_name:'upload_imgs',
            input_name: 'images',
            thumb_input_name:"thumb",
            numUp:10 //  1就是单图上传
		},
		init: function(elem, options){
			this.config = $.extend({}, this.defaults, this.options);
			console.log(this.$elem[0].files);
			var self = this;
			this.$elem.change(function () {
		        var fileList = self.$elem[0].files;
		        var numUp = self.$container.find(".up-img-list").length;
		        var totalNum = numUp + fileList.length;
		        if ( fileList.length > self.config.numUp || totalNum > self.config.numUp ) {
		        	if(self.config.numUp == 1){
		        		self.createHtml(fileList,self.config);
		        	}else{
		            	alert("上传图片数目不可以超过"+ self.config.numUp +"个，请重新选择");
		        	}
		        } else if (numUp < self.config.numUp) {
		            self.createHtml(fileList,self.config);
		        }
		        $(this).val("");
		    });
		    this.$container.delegate(".close", "click", function () {
		        delParent = $(this).parent();
		        var photo = $(this).next(".up-img").attr("src");
		        var thumb = delParent.find("input[name='"+self.config.input_name+"[]']").attr("value");
		        var data = {'photo':photo,'thumb':thumb};
		        $.ajax({
					type : 'post',
					url : self.config.remove_target, //接口
					data:data,
					success:function(data){
						delParent.remove();
					}
			    });
		    });
		    this.$container.delegate(".magnify", "click", function () {
		    	var e = $(this).parent().find("input[name='"+self.config.input_name+"[]']").attr("value");
		        $("body").append('<div class="imgPreviewFull"><a class="iconfont icon-close close"></a><i class="loadding"></i></div>');
		        var i = new Image;
	            i.src = e, i.onload = function () {
	                $(".imgPreviewFull .loadding").remove(), $(".imgPreviewFull").append(i)
	            }, $(".imgPreviewFull .close").one("click", function () {
	                $(".imgPreviewFull").remove()
	            })
		    })
		},
		validate : function( files,opt ) { 
	      	var arrFiles = [];
	        for (var i = 0, file; file = files[i]; i++) {
	            var newStr = file.name.split("").reverse().join("");
	            if (newStr.split(".")[0] != null) {
	                var type = newStr.split(".")[0].split("").reverse().join("");
	                if (jQuery.inArray(type, opt.fileType) > -1) {
	                    if (file.size >= opt.fileSize) {
	                        alert(file.name + '"文件大小过大');
	                    } else {
	                        arrFiles.push(file);
	                    }
	                } else {
	                    alert(file.name + '"上传类型不符合');
	                }
	            } else {
	                alert(file.name + '"没有类型, 无法识别');
	            }
	        }
	        return arrFiles;
	    },
	    createHtml : function(fileList,opt){
	    	var fileList = this.validate(fileList,opt);
            var str = '';
            for (var i = 0; i < fileList.length; i++) {
            	var formData = new FormData();
		        formData.append('file',fileList[i]);
		    	$.ajax({
					type : 'post',
					url : opt.upload_target,
					data:formData,
					cache: false,
					contentType: false,    
					processData: false,   
					success:function(data){
						str = '<section class="up-img-list loading">'+
				            '<span class="up-span"></span>'+
				            '<i class="iconfont icon-magnifier magnify" title="查看大图"></i>'+
							'<i class="iconfont icon-close close" title="删除图片"></i>'+
				            '<img class="up-img" src="'+data.thumb+'">'+
				            '<input name="'+opt.input_name+'[]" value="'+data.photo+'" type="hidden">'+
				            '<input name="'+opt.thumb_input_name+'[]" value="'+data.thumb+'" type="hidden">'+
				        '</section>';
				        if(opt.numUp == 1){
				        	$(".up-img-list").eq(0).remove();
				        }	
				        $(".upload-button").before(str);
					}
			    });
            }
	    }
	};

	Uploader.defaults = Uploader.prototype.defaults;
	$.fn.Uploader = function(options) {
		return this.each(function() {
			new Uploader(this, options).init();
		});
	};

})(jQuery,window,document);